const express = require('express')
const { Server } = require('socket.io')
const { createServer } = require('http')

const messageTime = 1 * 1000

const app = express()
app.all('*', (req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Methods', 'GET,PO ST')
  next()
})

const httpServer = createServer(app)
const io = new Server(httpServer, { cors: true })

io.on('connection', (socket) => {
  console.log('客户端已连接')
  socket.on('message', function (msg) {
    console.log(msg)
    socket.send('服务器' + msg)
  })

  setInterval(() => {
    console.log('send Message')
    socket.emit('hello', { name: 'world' })
  }, messageTime)
})

httpServer.listen(8066, () => {
  console.log('Server is open')
})
